﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Net;

using EHTWebsite.Code;
using EHTWebsiteProject.Code.BLL;
using System.Resources;
using System.Threading;
using System.Globalization;
using System.Text;

namespace EHTWebsiteProject.Administrator
{
    public partial class EHTProducts : System.Web.UI.Page
    {
        public Boolean IsVN = true;
        private String languageCode = "vi-VN";
        private DataTable dtProductCategorys = new DataTable();
        private ResourceManager rm = new ResourceManager("Resources.SiteMap", System.Reflection.Assembly.Load("App_GlobalResources"));
        private Int32 DanhMucID = -1;
        private Int32 pageIndex = 1;
        private Int32 pageSize = 30;
        private Int32 totalRecord;
        private String Search = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                AjaxPro.Utility.RegisterTypeForAjax(typeof(EHTWebsiteProject.Administrator.EHTProducts));
                dtProductCategorys = DanhMucSanPhamProvider.GetDanhMucSanPhams(-1, "", "").Tables[0];

                try
                {
                    languageCode = Session[HangSo.LANGUAGE_CODE].ToString();
                    Session["NgonNgu"] = languageCode;
                    if (languageCode == "en-us")
                    {
                        IsVN = false;
                    }

                }
                catch (Exception ex)
                {
                }

                try
                {
                    DanhMucID = Int32.Parse(Request.QueryString["DanhMucID"].ToString());
                    Session["DanhMucID"] = DanhMucID.ToString();
                }
                catch
                {
                    DanhMucID = -1;
                }

                try
                {
                    Search = Request.QueryString["Search"].ToString();
                    Session["Search"] = Search.ToString();
                }
                catch
                {
                    Search = "";
                }

                try
                {
                    pageIndex = Int32.Parse(Request.QueryString["PageIndex"].ToString());
                    Session["PageIndex"] = pageIndex.ToString();
                }
                catch
                {
                    pageIndex = 1;
                }

                try
                {
                    pageSize = Int32.Parse(Request.QueryString["PageSize"].ToString());
                    Session["PageSize"] = pageSize.ToString();
                }
                catch
                {
                    pageSize = 30;
                }

                Thread.CurrentThread.CurrentCulture = new CultureInfo(languageCode);
                LoadLanguage(Thread.CurrentThread.CurrentCulture);
                ddlSize.SelectedValue = pageSize.ToString();
                try
                {
                    loadProducts(Int32.Parse(Session["DanhMucID"].ToString()));
                }
                catch
                {
                    loadProducts(DanhMucID);
                }

                CreateDDLCategory(0, 0);
                if (IsVN == true)
                    this.ddlDanhmucSanPham.Items.Insert(0, new ListItem(HangSo.DanhMuc, "0"));
                else
                    this.ddlDanhmucSanPham.Items.Insert(0, new ListItem(HangSo.DanhMucOther, "0"));
                ddlDanhmucSanPham.SelectedValue = DanhMucID.ToString();                
            }
        }
        /// <summary>
        /// Ham load ngon ngu
        /// </summary>
        /// <param name="ci"></param>
        public void LoadLanguage(CultureInfo ci)
        {
            lbAddNew.Text = rm.GetString("lbAddNew", ci);
            lbDel.Text = rm.GetString("lbDel", ci);
            lbEdit.Text = rm.GetString("lbEdit", ci);
            lbHelp.Text = rm.GetString("lbHelp", ci);
            lbProduct.Text = rm.GetString("lbProduct", ci);
            lbHienThi.Text = rm.GetString("lbHienThi", ci);
            lbTat.Text = rm.GetString("lbTat", ci);
            lbBat.Text = rm.GetString("lbBat", ci);
            lbProducts.Text = rm.GetString("lbProducts", ci);
            lbCategory.Text = rm.GetString("lbCategory", ci);
            lbCauHinh.Text = rm.GetString("lbCauHinh", ci);
        }
        /// <summary>
        /// Ham load Product
        /// </summary>
        [AjaxPro.AjaxMethod]
        public SanPham GetSanPham()
        { 
            SanPham theSanPham = new SanPham();
            theSanPham.DanhMucID = DanhMucID;
            if (IsVN == true)
            {
                theSanPham.TenSanPhamVN = Search;
                theSanPham.TenSanPhamOther = "";
            }
            else
            {
                theSanPham.TenSanPhamOther = Search;
                theSanPham.TenSanPhamVN = "";
            }
            return theSanPham;
        }

        [AjaxPro.AjaxMethod]
        public void loadProducts(Int32 DanhMucID)
        {
             Int32 PageSize;
            try
            {
                PageSize = Int32.Parse(Session["PageSize"].ToString());
            }
            catch
            {
                PageSize = 30;
            }
            if (PageSize == -1)
                PageSize = 10000;
            if (Session[HangSo.LANGUAGE_CODE].ToString() == "vi-VN")
            {
                rpProducts.DataSource = SanPhamProvider.GetSanPhamsByFilter(GetSanPham(), pageIndex, PageSize, out totalRecord);
                rpProducts.DataBind();
                pnSanPhamOther.Visible = false;
            }
            else
            {
                rpProductsOther.DataSource = SanPhamProvider.GetSanPhamsByFilter(GetSanPham(), pageIndex, PageSize, out totalRecord);
                rpProductsOther.DataBind();
                pnSanPham.Visible = false;
            }
            this.PaggingControl1.PageIndex = pageIndex;
            this.PaggingControl1.TotalRecord = totalRecord;
            this.PaggingControl1.PageURL = "EHTProducts.aspx?DanhMucID=" + DanhMucID.ToString();
        }


        /// <summary>
        /// Ham check all or uncheck
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        public void CheckAll(object sender, System.EventArgs e)
        {
            CheckBox ckAll = (CheckBox)sender;
            if (Session[HangSo.LANGUAGE_CODE].ToString() == "vi-VN")
            {
                if (ckAll.Checked)
                {
                    foreach (RepeaterItem rp in rpProducts.Items)
                    {
                        CheckBox ckMenu = (CheckBox)rp.FindControl("ckMenu");
                        ckMenu.Checked = true;
                    }
                }
                else
                {
                    foreach (RepeaterItem rp in rpProducts.Items)
                    {
                        CheckBox ckMenu = (CheckBox)rp.FindControl("ckMenu");
                        ckMenu.Checked = false;
                    }
                }
            }
            else
            {
                if (ckAll.Checked)
                {
                    foreach (RepeaterItem rp in rpProductsOther.Items)
                    {
                        CheckBox ckMenu = (CheckBox)rp.FindControl("ckMenu");
                        ckMenu.Checked = true;
                    }
                }
                else
                {
                    foreach (RepeaterItem rp in rpProductsOther.Items)
                    {
                        CheckBox ckMenu = (CheckBox)rp.FindControl("ckMenu");
                        ckMenu.Checked = false;
                    }
                }
            }
        }

        protected void ImaTat_Click(object sender, ImageClickEventArgs e)
        {
            ArrayList arr = new ArrayList();
            if (Session[HangSo.LANGUAGE_CODE].ToString() == "vi-VN")
            {
                foreach (RepeaterItem rp in rpProducts.Items)
                {
                    CheckBox ckMenu = (CheckBox)rp.FindControl("ckMenu");
                    Label lbDelID = (Label)rp.FindControl("lbDelID");
                    if (ckMenu.Checked == true)
                    {
                        arr.Add(lbDelID.Text);
                    }
                }
            }
            else
            {
                foreach (RepeaterItem rp in rpProductsOther.Items)
                {
                    CheckBox ckMenu = (CheckBox)rp.FindControl("ckMenu");
                    Label lbDelID = (Label)rp.FindControl("lbDelID");
                    if (ckMenu.Checked == true)
                    {
                        arr.Add(lbDelID.Text);
                    }
                }
            }
            for (int i = 0; i < arr.Count; i++)
                SanPhamProvider.ChangePublish(Int32.Parse(arr[i].ToString()),false);
            loadProducts(DanhMucID);
        }

        protected void ImgBat_Click(object sender, ImageClickEventArgs e)
        {
            ArrayList arr = new ArrayList();
            if (Session[HangSo.LANGUAGE_CODE].ToString() == "vi-VN")
            {
                foreach (RepeaterItem rp in rpProducts.Items)
                {
                    CheckBox ckMenu = (CheckBox)rp.FindControl("ckMenu");
                    Label lbDelID = (Label)rp.FindControl("lbDelID");
                    if (ckMenu.Checked == true)
                    {
                        arr.Add(lbDelID.Text);
                    }
                }
            }
            else
            {
                foreach (RepeaterItem rp in rpProductsOther.Items)
                {
                    CheckBox ckMenu = (CheckBox)rp.FindControl("ckMenu");
                    Label lbDelID = (Label)rp.FindControl("lbDelID");
                    if (ckMenu.Checked == true)
                    {
                        arr.Add(lbDelID.Text);
                    }
                }
            }
            for (int i = 0; i < arr.Count; i++)
                SanPhamProvider.ChangePublish(Int32.Parse(arr[i].ToString()), true);
            loadProducts(DanhMucID);
        }

        protected void ImgDel_Click(object sender, ImageClickEventArgs e)
        {
            ArrayList arr = new ArrayList();
            if (Session[HangSo.LANGUAGE_CODE].ToString() == "vi-VN")
            {
                foreach (RepeaterItem rp in rpProducts.Items)
                {
                    CheckBox ckMenu = (CheckBox)rp.FindControl("ckMenu");
                    Label lbDelID = (Label)rp.FindControl("lbDelID");
                    if (ckMenu.Checked == true)
                    {
                        arr.Add(lbDelID.Text);
                    }
                }
            }
            else
            {
                foreach (RepeaterItem rp in rpProductsOther.Items)
                {
                    CheckBox ckMenu = (CheckBox)rp.FindControl("ckMenu");
                    Label lbDelID = (Label)rp.FindControl("lbDelID");
                    if (ckMenu.Checked == true)
                    {
                        arr.Add(lbDelID.Text);
                    }
                }  
            }
            for (int i = 0; i < arr.Count; i++)
                SanPhamProvider.DeleteSanPhamBySanPhamID(Int32.Parse(arr[i].ToString()));
            loadProducts(DanhMucID);
        }

        protected void ImgEdit_Click(object sender, ImageClickEventArgs e)
        {
            Int32 ID = 0;
            Int32 Count = 0;
            if (Session[HangSo.LANGUAGE_CODE].ToString() == "vi-VN")
            {
                foreach (RepeaterItem rp in rpProducts.Items)
                {
                    CheckBox ckMenu = (CheckBox)rp.FindControl("ckMenu");
                    Label lbDelID = (Label)rp.FindControl("lbDelID");
                    if (ckMenu.Checked == true)
                    {
                        ID = Int32.Parse(lbDelID.Text);
                        Count++;
                    }
                }
            }
            else
            {
                foreach (RepeaterItem rp in rpProductsOther.Items)
                {
                    CheckBox ckMenu = (CheckBox)rp.FindControl("ckMenu");
                    Label lbDelID = (Label)rp.FindControl("lbDelID");
                    if (ckMenu.Checked == true)
                    {
                        ID = Int32.Parse(lbDelID.Text);
                        Count++;
                    }
                }
            }
            if (Count > 1 || Count == 0)
            {
                String messa = "";
                if (IsVN == true)
                    messa = HangSo.Eorr_Edit;
                else
                    messa = HangSo.Eorr_EditOther;
                ltrErorr.Text = HelpMethod.ErorrLogin(messa);
            }
            else
            {
                Response.Redirect("EHTProductUI.aspx?productID=" + ID.ToString());
            }
        }

        protected void rpProducts_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Label lbStatus = (Label)e.Item.FindControl("lbStatus");
            Image ImagStatus = (Image)e.Item.FindControl("ImagStatus");
            try
            {
                if (lbStatus.Text == "True")
                    ImagStatus.ImageUrl = "~/images/tick.png";
                else
                    ImagStatus.ImageUrl = "~/images/Close.png";
            }
            catch
            { 
                
            }
        }

        /// <summary>
        /// Ham load danh muc san pham
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CreateDDLCategory(Int32 ChuyenMucChaID, Int32 level)
        {
            String preString = "";

            for (Int32 i = 0; i < level; ++i)
            {
                preString += "--";
            }

            DataRow[] drCategorysSub = dtProductCategorys.Select("ChuyenMucChaID = " + ChuyenMucChaID.ToString());
            Int32 amountOfCategorySub = drCategorysSub.Count();

            //Điểm dừng đệ quy
            if (amountOfCategorySub == 0)
                return;

            for (Int32 i = 0; i < amountOfCategorySub; ++i)
            {
                Int32 subCategoryID = Int32.Parse(drCategorysSub[i]["DanhMucID"].ToString());
                ListItem li;
                if(IsVN==true)
                    li = new ListItem(preString + drCategorysSub[i]["TenDanhMucVN"].ToString(), drCategorysSub[i]["DanhMucID"].ToString());
                else
                    li = new ListItem(preString + drCategorysSub[i]["TenDanhMucOther"].ToString(), drCategorysSub[i]["DanhMucID"].ToString());
                this.ddlDanhmucSanPham.Items.Add(li);
                CreateDDLCategory(subCategoryID, level + 1);
            }
        }

        protected void ddlDanhmucSanPham_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect("EHTProducts.aspx?DanhMucID=" + ddlDanhmucSanPham.SelectedValue);
        }

        protected void ImagSearch_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("EHTProducts.aspx?Search="+txtsearch.Text);
        }

        protected void ddlSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect("EHTProducts.aspx?PageSize=" + ddlSize.SelectedValue);
        }

        protected void rpProducts_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            String cmdName = e.CommandName;
            Int32 SanPhamID = -1;
            try
            {
                SanPhamID = Int32.Parse(e.CommandArgument.ToString());
            }
            catch (Exception ex)
            {
            }

            if (cmdName == "change_number_of_order")
            {
                try
                {
                    Int32 numberOfOrder = Int32.Parse(((TextBox)e.Item.FindControl("txtNumberOfOrder")).Text.Trim());
                    SanPhamProvider.UpdateNumberOfOrderBySanPhamID(SanPhamID, numberOfOrder);
                }
                catch (Exception ex)
                {

                }

                loadProducts(DanhMucID);
            }
            else if (cmdName == "save_all")
            {
                foreach (RepeaterItem item in rpProducts.Items)
                {
                    Int32 numberOfOrder = Int32.Parse(((TextBox)item.FindControl("txtNumberOfOrder")).Text.Trim());
                    SanPhamID = Int32.Parse(((Label)item.FindControl("lbDelID")).Text.Trim());
                    SanPhamProvider.UpdateNumberOfOrderBySanPhamID(SanPhamID, numberOfOrder);
                }

                loadProducts(DanhMucID);
            }
        }

        protected void rpProductsOther_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            String cmdName = e.CommandName;
            Int32 SanPhamID = -1;
            try
            {
                SanPhamID = Int32.Parse(e.CommandArgument.ToString());
            }
            catch (Exception ex)
            {
            }

            if (cmdName == "change_number_of_order")
            {
                try
                {
                    Int32 numberOfOrder = Int32.Parse(((TextBox)e.Item.FindControl("txtNumberOfOrder")).Text.Trim());
                    SanPhamProvider.UpdateNumberOfOrderBySanPhamID(SanPhamID, numberOfOrder);
                }
                catch (Exception ex)
                {

                }

                loadProducts(DanhMucID);
            }
            else if (cmdName == "save_all")
            {
                foreach (RepeaterItem item in rpProductsOther.Items)
                {
                    Int32 numberOfOrder = Int32.Parse(((TextBox)item.FindControl("txtNumberOfOrder")).Text.Trim());
                    SanPhamID = Int32.Parse(((Label)item.FindControl("lbDelID")).Text.Trim());
                    SanPhamProvider.UpdateNumberOfOrderBySanPhamID(SanPhamID, numberOfOrder);
                }

                loadProducts(DanhMucID);
            }
        }

        protected void rpProductsOther_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Label lbStatus = (Label)e.Item.FindControl("lbStatus");
            Image ImagStatus = (Image)e.Item.FindControl("ImagStatus");
            try
            {
                if (lbStatus.Text == "True")
                    ImagStatus.ImageUrl = "~/images/tick.png";
                else
                    ImagStatus.ImageUrl = "~/images/Close.png";
            }
            catch
            {

            }
        }

        protected void ImgCauHinh_Click(object sender, ImageClickEventArgs e)
        {
            Session.Remove("ArrayListConfig");
            ArrayList arr = new ArrayList();
            if (Session[HangSo.LANGUAGE_CODE].ToString() == "vi-VN")
            {
                foreach (RepeaterItem rp in rpProducts.Items)
                {
                    Label lbDelID = (Label)rp.FindControl("lbDelID");
                    String str = lbDelID.Text;
                    arr.Add(str);

                }
            }
            else
            {
                foreach (RepeaterItem rp in rpProductsOther.Items)
                {
                    Label lbDelID = (Label)rp.FindControl("lbDelID");
                    String str = lbDelID.Text;
                    arr.Add(str);

                }
            }
            if (arr.Count > 0)
            {
                Session["ArrayListConfig"] = arr;
                Response.Redirect("EHTConfigProduct.aspx");
            }
            else
                return;
        }
        
    }
}